import EventTable from "../components/EventTable.jsx";
import {useEffect, useState} from "react";
import EventFilter from "../components/EventFilter.jsx";
import {Link} from "react-router";

export default function EventList(){
  const [isPending, setIsPending] = useState(false)
  const [events, setEvenets] = useState([])
  const [pagination, setPagination] = useState({})
  const [filter,setFilter] = useState({per_page:5,page:1,title:'',category:'',tags:new Set([]),start_at:'',end_at:'',tag_rel:'or'})

  useEffect(() => {
    getEvents();
  }, [filter]);
  async function getEvents(){
    let url = `http://127.0.0.1:8000/api/v1/events`
    let query = []
    if(filter.page) query.push(`page=${filter.page}`)
    if(filter.per_page) query.push(`per_page=${filter.per_page}`)
    if(filter.title) query.push(`title=${filter.title}`)
    if(filter.category) query.push(`category=${filter.category}`)
    if(filter.start_at) query.push(`start_at=${filter.start_at}`)
    if(filter.end_at) query.push(`end_at=${filter.end_at}`)
    if(filter.tags.size){
      Array.from(filter.tags).forEach(tag=>{
        query.push(`tags[]=${tag}`)
      })
    }
    if(filter.tag_rel) query.push(`tag_rel=${filter.tag_rel}`)
    if(query.length) url += '?' + query.join('&')

    console.log("URL:",url)
    setIsPending(true)
    const response = await fetch(url)
    if((await response).status===200){
      const data = (await response.json()).data
      setEvenets(data.events)
      //console.table(data.events)
      setPagination(data.pagination);
    }
    setIsPending(false)
  }
  async function handleFilterChange(prop,value,resetPage=false) {
    if(resetPage)
    setFilter(prev =>  ({...prev, [prop]: value,page:1}))
    else
      setFilter(prev =>  ({...prev, [prop]: value}))
  }

  function gotoPage(pageNo) {
    setFilter(prev => ({...prev, page: pageNo}))
  }
    return (
        <div className="container mx-auto py-8 px-4 sm:px-6 lg:px-8">
      <div className="flex flex-col sm:flex-row justify-between items-center mb-6">
        <h1 className="text-3xl font-bold text-gray-800 mb-4 sm:mb-0">Events</h1>
        <button className="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600">
          Add New Event
        </button>
      </div>

      {/* Filters */}
      <EventFilter handle={handleFilterChange}/>


      {/* Event Table (Desktop) */}
      <div className="hidden md:block">
        {isPending?(
            <>
              <p>Loading...</p>
            </>
        ): (
            <table className="w-full border-collapse bg-white rounded-lg shadow-md mb-6">
              <thead>
              <tr className="bg-gray-200">
                <th className="p-4 text-left text-gray-700">Name</th>
                <th className="p-4 text-left text-gray-700">Category</th>
                <th className="p-4 text-left text-gray-700">Time</th>
                <th className="p-4 text-left text-gray-700">Participants</th>
                <th className="p-4 text-left text-gray-700">Comments</th>
                <th className="p-4 text-left text-gray-700">Tags</th>
                <th className="p-4 text-left text-gray-700">Actions</th>
              </tr>
              </thead>
              <tbody>
              {events.map(event => (
                  <tr className="border-b" key={event.id}>
                    <td className="p-4">
                      <Link to={`/events/${event.id}`} className="text-blue-500 hover:underline">{event.title}</Link>
                    </td>
                    <td className="p-4">{event.category.name}</td>
                    <td className="p-4">{event.start_at} - {event.end_at}</td>
                    <td className="p-4">
                      <div className="flex items-center space-x-2">
                        <div className="relative w-2/3 bg-gray-200 rounded-full h-6 overflow-hidden" role="progressbar"
                             aria-valuenow="5" aria-valuemin="0" aria-valuemax="100" aria-label="Participants progress">
                          <div style={{width: `${(event.participant_count/event.capacity)*100}%`}}
                              className="h-6 rounded-l-full bg-[#10b981]"></div>
                        </div>
                        <span className="text-gray-700 text-sm font-semibold" title="5/100 participants">{event.participant_count}/{event.capacity}</span>
                      </div>
                    </td>
                    <td className="p-4">{event.comment_count}</td>
                    <td className="p-4">
                      {event.tags.map(tag=>(
                          <span className="ml-2" key={tag.id}>{tag.name}</span>
                      ))}
                    </td>
                    <td className="p-4">
                      <a href="edit-event.html" className="text-blue-500 hover:underline mr-2">Edit</a>
                      <a href="#" className="text-red-500 hover:underline">Delete</a>
                    </td>
                  </tr>
              ))}

              </tbody>
            </table>
        )}

      </div>

          {/* Event Cards (Mobile) */}
          <div className="md:hidden space-y-4 mb-6">
            {events.map(event => (
                <div className="bg-white p-4 rounded-lg shadow-md" key={event.id}>
                  <h3 className="text-lg font-semibold text-gray-800">
                    <Link to={`/events/${event.id}`}  className="text-blue-500 hover:underline">{event.title}</Link>
                  </h3>
                  <p className="text-gray-600">Category: {event.category.name}</p>
                  <p className="text-gray-600">Time: {event.start_at} - {event.end_at}</p>
                  <p className="text-gray-600">Participants: {event.participant_count} / {event.capacity}</p>
                  <p className="text-gray-600">Comments: {event.comment_count}</p>
                  <p className="text-gray-600">Tags: {event.tags.map(tag=>(
                      <span className="ml-2" key={tag.id}>{tag.name}</span>
                  ))}</p>
                  <div className="mt-2">
                    <a href="#" className="text-blue-500 hover:underline mr-2">Edit</a>
                    <a href="#" className="text-red-500 hover:underline">Delete</a>
                  </div>
                </div>
            ))}


          </div>

          {/* Pagination --> */}
          <div className="flex flex-col sm:flex-row justify-between items-center space-y-4 sm:space-y-0">
            <p className="text-gray-700">
              Showing <span id="current-page">{pagination.current_page}</span> of
              <span id="total-pages">{pagination.last_page}</span> pages (<span
                id="total-records">{pagination.total}</span>
              records)
            </p>
            <div className="flex items-center space-x-2">
              <button id="prev-page"
                      disabled={pagination.current_page <= 1}
                      onClick={() => handleFilterChange('page', pagination.current_page - 1)}
                      className="cursor-pointer bg-gray-300 text-gray-700 px-3 py-1 rounded hover:bg-gray-400 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Previous
              </button>
              <span className="text-gray-700">Page <span id="page-number">{pagination.current_page}</span></span>
              <button
                  disabled={pagination.current_page>=pagination.last_page}
                  id="next-page"
                  onClick={()=>handleFilterChange('page',pagination.current_page+1)}
                  className="cursor-pointer bg-gray-300 text-gray-700 px-3 py-1 rounded hover:bg-gray-400 disabled:opacity-50 disabled:cursor-not-allowed">
            Next
          </button>
        </div>
        <div className="flex items-center space-x-2">
          <label className="text-gray-700">Records per page:</label>
          <select id="per-page" className="p-2 border rounded" value={pagination.per_page} onChange={(e)=>{handleFilterChange('per_page',e.target.value,true)}}>
            <option value="5">5</option>
            <option value="10">10</option>
            <option value="20">20</option>
            <option value="50">50</option>
          </select>
        </div>
          </div>
        </div>
    )
}